/** 
  考核成绩录入表
*/
<template>
  <div class="assess-score-table-container">
    <table class="table-style-baseinfos">
      <tbody>
        <tr>
          <td class="text-right-background-color">{{ $t('templateSetting.templateName') }}:</td>
          <td class="text-left-background-none">{{ assessScoreInfo.templateName }}</td>
          <td class="text-right-background-color">{{ $t('templateSetting.baseLevel') }}:</td>
          <td class="text-left-background-none">{{ assessScoreInfo.baseLevel | baseLevel }}</td>
        </tr>
        <tr>
          <td class="text-right-background-color">{{ $t('templateSetting.description') }}:</td>
          <td class="text-left-background-none" colspan="3">{{ assessScoreInfo.description }}</td>
        </tr>
      </tbody>
    </table>
    <el-form :model="assessScoreForm" ref="assessScoreForm" :rules="rulesForm">
      <table class="table-style-baseinfo">
        <thead>
          <tr>
            <th class="text-center-background-color">{{ $t('asesmentSetting.assessmentIndex') }}</th>
            <!-- <th class="text-center-background-color">{{ $t('asesmentSetting.assessmentIndexDesc') }}</th>
            <th class="text-center-background-color">{{ $t('asesmentSetting.assessmentIndexWeig') }}</th> -->
            <th class="text-center-background-color">{{ $t('asesmentSetting.assessmentDetails') }}</th>
            <th class="text-center-background-color">{{ $t('asesmentSetting.assessmentDetailsDesc') }}</th>
            <!-- <th class="text-center-background-color">{{ $t('asesmentSetting.assessmentDetailsWeig') }}</th> -->
            <th class="text-center-background-color">{{ $t('baseAssess.score') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in assessScoreForm.dataList" :key="index">
            <td v-if="item.subCount" :rowspan="item.subCount" class="text-center-background">{{ item.itemName }}</td>
            <!-- <td v-if="item.subCount" :rowspan="item.subCount" class="text-center-background">{{ item.itemDescription }}</td>
            <td v-if="item.subCount" :rowspan="item.subCount" class="text-center-background">{{ item.itemWeight }}</td> -->
            <td class="text-center-background">{{ item.detailName }}</td>
            <td class="text-center-background">{{ item.detailDescription }}</td>
            <!-- <td class="text-center-background">{{ item.detailWeight }}</td> -->
            <td class="text-center-background self-score">
              <el-form-item :prop="'dataList.' + index + '.detailScore'" :rules="[{ validator: validateScore, trigger: 'blur' }]">
                <el-input v-model.trim="item.detailScore" :placeholder="$t('common.pla.pleaseInput')"></el-input>
              </el-form-item>
            </td>
          </tr>
          <tr>
            <td style="text-align: center;" colspan="3">{{ $t('baseAssess.totalScore') }}</td>
            <td>{{ totalScore }}</td>
          </tr>
        </tbody>
      </table>
    </el-form>
    <div class="operate-info-container">
      <el-button @click="cancel()">{{$t('common.btn.cancel')}}</el-button>
      <el-button type="primary" @click="confirmInfo()">{{$t('common.btn.confirm')}}</el-button>
    </div>
    <cancel-info :parentInnerVisible="parentInnerVisible" @confirm-and-close="confirmAndClose" @confirm-close="confirmClose" @cancel-to-close="cancelToClose"></cancel-info>
  </div>
</template>
<script>
import cancelInfo from '../common/cancelInfo';
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
export default {
  components: {
    'cancel-info': cancelInfo
  },
  props: {
    dataListProp: {
      type: Object,
      default: () => {}
    },
    baseExamineId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      userInfo: {},
      assessScoreInfo: {},
      totalScore: 0,
      assessScoreForm: {
        dataList: []
      },
      rulesForm: {
        detailScore: [
          {
            validator: this.validateScore,
            trigger: 'blur'
          }
        ]
      },
      parentInnerVisible: false
    }
  },
  filters: {
    baseLevel(val) {
      switch (val) {
        case '1':
          return '校级'
        case '2':
          return '院级'
        default:
          return val
      }
    }
  },
  created() {
    
  },
  mounted() {
    // 获取当前用户auths权限
    let sessiondata = JSON.parse(localStorage.getItem("sessiondata"))
    if (sessiondata) {
      if (sessiondata.mockUser || sessiondata.user) {
        this.userInfo = sessiondata.mockUser || sessiondata.user
      }
    }
  },
  methods: {
    validateScore(rule, value, callback) {
      let index = rule.field.split('.')[1]
      let expReg = /^(\d{0,3})(\.\d{1,2})?$/
      if (!value && value !== 0) {
        callback(new Error(this.$t('baseAssess.requireScore')))
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('baseAssess.validateScore')))
      } else if (Number(value) > 100) {
        callback(new Error(this.$t('baseAssess.validateScore')))
      } else {
        callback()
      }
    },
    numMulti(num1, num2) {
      let baseNum = 0
      try {
        baseNum += num1.toString().split(".")[1].length
      } catch (e) {

      }
      try {
        baseNum += num2.toString().split(".")[1].length
      } catch (e) {

      }
      return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum)
    },
    // 实时计算总得分
    getTotalScore() {
      let copyInfo = JSON.parse(JSON.stringify(this.assessScoreForm.dataList))
      let sourceInfo = JSON.parse(JSON.stringify(this.dataListProp.itemList))
      let totalScore = 0
      sourceInfo.forEach((element, index, array) => {
        element.detailList.forEach((detailItem, detailIndex) => {
          copyInfo.map((formItem, formIndex) => {
            if (detailItem.detailId === formItem.detailId) {
              detailItem.detailScore = formItem.detailScore
            }
          })
        })
      })
      sourceInfo.forEach((element, index, array) => {
        let everyGroupScore = element.itemWeight
        let everyGroupDetails = 0
        element.detailList.forEach((detailItem, detailIndex) => {
          everyGroupDetails = everyGroupDetails + this.numMulti(detailItem.detailWeight, detailItem.detailScore)
        })
        totalScore = totalScore + this.numMulti(everyGroupScore, everyGroupDetails)
      })
      if (totalScore.toString() != 'NaN' && typeof(totalScore) === 'number') {
        this.totalScore = totalScore === 0 ? 0 : totalScore.toFixed(2)
      } else {
        this.totalScore = 0
      }
    },
    // 取消
    cancel() {
      let allIsEmpty = this.totalScore === 0
      if (allIsEmpty) {
        this.$emit('confirm-to-close-score-table')
      } else {
        this.parentInnerVisible = true
      }
    },
    cancelToClose() {
      this.parentInnerVisible = false
    },
    // 确认关闭提示框
    confirmClose() {
      this.parentInnerVisible = false
      this.$emit('confirm-to-close-score-table')
    },
    // 确定
    confirmInfo() {
      this.$refs['assessScoreForm'].validate((valid) => {
        if (valid) {
          let baseGradeDetailList = []
          baseGradeDetailList = this.assessScoreForm.dataList.map(item => {
            return {
              "id": item.baseGradeDetailId,
              "itemId": item.itemId,
              "itemName": item.itemName,
              "detailId": item.detailId,
              "detailName": item.detailName,
              "score": Number(item.detailScore)
            }
          })
          let params = {
            "id": this.assessScoreInfo.baseGradeId,
            "account": this.userInfo.uid,
            "baseExamineId": this.baseExamineId,
            "score": this.totalScore,
            "baseGradeDetailList": baseGradeDetailList
          }
          graduateStudentApi.specialSaveAssessScore(params).then(res => {
            if (res.code === 200) {
              this.$emit('record-experts-score', {
                totalScore: this.totalScore,
                baseGradeId: res.data
              })
            }
          })
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error")
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus()
            }
          }, 1)
        }
      })
    },
    // 确定并保存
    confirmAndClose() {
      this.parentInnerVisible = false
      this.confirmInfo()
    }
  },
  watch: {
    dataListProp: {
      handler(newVal) {
        this.assessScoreInfo = JSON.parse(JSON.stringify(newVal))
        if (this.assessScoreInfo.itemList && Array.isArray(this.assessScoreInfo.itemList) && this.assessScoreInfo.itemList.length > 0) {
          this.assessScoreInfo.itemList.map((item, index) => {
            if (item.detailList && item.detailList.length > 0) {
              item.detailList.map((subItem, subIndex, subArray) => {
                if (subIndex === 0) {
                  subItem['subCount'] = subArray.length
                }
                subItem['detailScore'] = subItem.score || subItem.score === 0 ? subItem.score : ''
                this.assessScoreForm.dataList.push({ ...item, ...subItem })
              });
            } else {
              item['detailName'] = ''
              item['detailDescription'] = ''
              item['detailWeight'] = ''
              item['subCount'] = 1
              item['detailScore'] = ''
              delete item.detailList
              this.assessScoreForm.dataList.push(item)
            }
          });
        } else {
          this.assessScoreForm.dataList = []
        }
      },
      deep: true,
      immediate: true
    },
    "assessScoreForm.dataList": {
      handler(newVal) {
        if (newVal.length > 0) {
          this.getTotalScore()
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .inner-breadcrumb {
    .breadcrumb {
      span {
        font-weight: normal;
        color: #aaa;
      }
      a {
        font-weight: normal;
        color: #aaa;
      }
      a:hover {
        color: #409eff;
      }
      .last {
        font-weight: bold !important;
        cursor: default !important;
      }
      .disable {
        cursor: default !important;
      }
    }
  }
  .condition-title-p {
    font-weight: 400;
    font-style: normal;
    color: #2b3b4e;
    font-size: 18px;
    margin-bottom: 15px;
  }
  .base-info-title {
    font-weight: 400;
    font-style: normal;
    font-size: 16px;
    color: #2b3b4e;
  }
  .table-style-baseinfos {
    table-layout: fixed;
    word-break: break-all;
    background-color: rgba(210, 212, 214, 1);
    box-sizing: border-box;
    border-width: 0.5px;
    border-style: solid;
    border-color: rgba(210, 212, 214, 1);
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    width: 100%;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #8896a7;
    margin-bottom: 20px;
  }
  .table-style-baseinfo {
    table-layout: fixed;
    word-break: break-all;
    background-color: rgba(210, 212, 214, 1);
    box-sizing: border-box;
    border-width: 0.5px;
    border-style: solid;
    border-color: rgba(210, 212, 214, 1);
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    width: 100%;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #8896a7;
    margin-bottom: 20px;
  }
  .table-style-baseinfos td {
    width: 25%;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #2b3b4e;
    height: 32px;
    padding: 0 10px;
  }
  .table-style-baseinfo td {
    width: 15%;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #2b3b4e;
    height: 32px;
    padding: 0 10px;
  }
  .self-score ::v-deep {
    width: 20%!important;
    .el-form-item {
      margin-bottom: 0!important;
    }
    .is-error {
      margin-bottom: 18px!important;
    }
  }
  .table-style-baseinfos .text-right-background-color {
    background-color: #fdfeff4d;
    text-align: right;
  }
  .table-style-baseinfo .text-right-background-color {
    background-color: #fdfeff4d;
    text-align: right;
  }
  .text-center-background-color {
    background-color: #fdfeff4d;
    text-align: center;
  }
  .text-center-background {
    text-align: center;
  }
  .text-left-background-none {
    text-align: left;
  }
  .sub-title {
    margin: 0 0 15px 5px;
    font-size: 17px;
    color: #2b3b4e;
  }
  .assess-score-table-container ::v-deep {
    .el-dialog__body {
      word-break: break-all!important;
    }
  }
  .operate-info-container {
    text-align: right;
  }
</style>